#!/bin/sh

times=0
provider="cmcc"
prev=0
cur=$(date +%s)
#检测三次外网是否接通
while [ $times -le 3 ]
do
  ping -c 1 114.114.114.114 1>/dev/null
  if [ ! $? ];
  then
    times=0
    break
  else
    times=$times+1
  fi
done

#没有接通，删除路由表，拨号
if [ $times -gt 0 ]
then
  times=0
  route del default
  pppd call $provider 1>/dev/null &
else
  res=$cur-$prev
  if [ $prev -lt 1262275200 ] || [ $res -gt 14400 ]
  then
    pkill remote_terminal
    /usr/sbin/remote_terminal 1>/dev/null &
    pkill mqtt_bash
    /home/mqtt_bash 1>/dev/null &
    /home/ntpcli
    if [ ! $? ]
    then
      prev=$(date +%s)
    fi
  fi
fi

while true
do
  #小于6次等待1min
  if [ $times -lt 6 ]
  then
    sleep 60
  fi
  ping -c 1 114.114.114.114 1>/dev/null
  if [ ! $? ]
  then
    times=0
  else
    times=$times+1
  fi
  case $times in
  0)
    res=$cur-$prev
      if [ $prev -lt 1262275200 ] || [ $res -gt 14400 ]
      then
        pkill remote_terminal
        /usr/sbin/remote_terminal 1>/dev/null &
        pkill mqtt_bash
        /home/mqtt_bash 1>/dev/null &
        /home/ntpcli
        if [ ! $? ]
        then
          prev=$(date +%s)
        fi
      fi
    ;;
  [1-2])
    pkill pppd
    pppd call $provider 1>/dev/null &
    ;;
  [3-4])
    /home/ltepwr -p 0
    /home/ltepwr -p 1
    ;;
  5)
    reboot
    ;;
  *)
    break
  esac
done